package com.access.boot.autoconfigure.apisdk.proxy;

import com.access.boot.autoconfigure.apisdk.GlobalConfiguration;
import com.access.boot.autoconfigure.apisdk.aop.Advice;
import com.access.boot.autoconfigure.apisdk.proxy.aop.EnhanceProxyInstance;
import com.access.boot.autoconfigure.apisdk.proxy.aop.ProxyFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Yangzhen
 * @date 2022/5/28 15:24
 * @since 1.0.0
 */
@Slf4j
public class ApiSdkAccessorFactory implements AccessorFactory {
    private GlobalConfiguration globalConfiguration;

    public ApiSdkAccessorFactory(GlobalConfiguration globalConfiguration) {
        this.globalConfiguration = globalConfiguration;
    }

    @Override
    public <T> T create(Class<T> openApiInterface) {
        // javassist 调用入口，存储增强类的代理对象
        EnhanceProxyInstance enhanceProxyInstance = new EnhanceProxyInstance(openApiInterface);
        // 原始接口的包装，生成的代理对象由 Spring 管理，代理对象的方法之前时会由 Aop 拦截
        ProxyFactory proxyFactory = new ProxyFactory(enhanceProxyInstance);
        List<Advice> advices = globalConfiguration.getAdvices();
        for (Advice advice : advices) {
            proxyFactory.addAdvice(advice);
        }
        return (T) proxyFactory.getProxy();
    }
}
